using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TapTap.Login;
using TapTap.Bootstrap;
using System.Threading.Tasks;
using System;
using TapTap.Common;

public class LoginManager : MonoBehaviour
{
    public TDSUser m_CurrentUser;
    public static LoginManager Instance;
    // Start is called before the first frame update

    async public Task<bool> IsAnonymous()
    {
        try
        {
            if (m_CurrentUser == null)
            {
                m_CurrentUser = await TDSUser.GetCurrent();
            }
            return m_CurrentUser.IsAnonymous;
        }
        catch (System.Exception e)
        {
            Debug.Log($"判断匿名状态失败： message:{e}");
            return false;
        }
    }

    async public Task<bool> IsLogin()
    {
        try
        {
            if (m_CurrentUser == null)
            {
                m_CurrentUser = await TDSUser.GetCurrent();
            }
            if (null == m_CurrentUser)
            {
                Debug.Log("当前未登录");
                return false;
            }
            else
            {
                Debug.Log("已登录");
                return true;
            }
        }
        catch (Exception e)
        {
            Debug.Log($"判断登陆状态失败： message:{e}");
            return false;
        }
    }

    async public Task Logout()
    {
        await TDSUser.Logout();
        m_CurrentUser = null;
    }

    async public Task<bool> LoginWithTapTap()
    {
        try
        {
            m_CurrentUser = await TDSUser.LoginWithTapTap();
            Debug.Log($"login sucess:{m_CurrentUser}");
            return true;
        }
        catch (Exception e)
        {
            if (e is TapException tapError)  // using TapTap.Common
            {
                Debug.Log($"encounter exception:{tapError.code} message:{tapError.message}");
                if (tapError.code == (int)TapErrorCode.ERROR_CODE_BIND_CANCEL) // 取消登录
                {
                    Debug.Log("登录取消");
                }
            }
            Debug.Log(e.Message);
            return false;
        }
    }

    async public Task<bool> LoginAnonymously()
    {
        try
        {
            // 通过 tdsUSer 给出用户唯一标识，如果有的话，
            m_CurrentUser = await TDSUser.LoginAnonymously();
            Debug.Log($"LoginAnonymously sucess:{m_CurrentUser}");
            return true;
        }
        catch (Exception e)
        {
            //登录失败
            Debug.Log($"{e.Source} : {e.Message}");
            return false;
        }
    }

    void Awake()
    {
        Instance = this;
    }
}
